﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Xml.Serialization;
using WebLib.AuthorizeService;
using Microsoft.AspNet.SignalR;
using log4net.Config;
using log4net;

namespace HinokyWeb
{
    // 참고: IIS6 또는 IIS7 클래식 모드를 사용하도록 설정하는 지침을 보려면 
    // http://go.microsoft.com/?LinkId=9394801을 방문하십시오.

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath("~/LogConfig.xml")));

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

        public override void Init()
        {
            PostAuthenticateRequest += (sender, args) =>
            {
                var req = HttpContext.Current.Request;

                if (req.Cookies.Count > 0 && req.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    var cookie = req.Cookies[FormsAuthentication.FormsCookieName];
                    if (cookie != null)
                    {
                        var str = cookie.Value;

                        var userIdentity = GetUserData(str);
                        //var principal = new Principal(userIdentity, userIdentity.UserRoles);
                        var principal = new GenericPrincipal(userIdentity, userIdentity.UserRoles);
                        HttpContext.Current.User = principal;
                    }
                }
            };

            base.Init();
        }

        private Identity GetUserData(string str)
        {
            var ticket = FormsAuthentication.Decrypt(str);
            var xs = new XmlSerializer(typeof(UserDataModel));
            if (ticket != null)
            {
                var sr = new StringReader(ticket.UserData);
                var userData = (UserDataModel)xs.Deserialize(sr);

                if (userData != null)
                {
                    return new Identity(userData.UserId, userData.UserName, userData.UserRoles);
                }

                return null;
            }

            return null;
        }
    }
}